package com.jthinker.dao.impl;

import com.jthinker.dao.BaseDao;
import com.jthinker.dao.CategoryDao;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/4/22 22:13
 */
@Repository
public class CategoryDaoImpl implements CategoryDao
{
    @Resource
    private BaseDao baseDao;

    @Override
    public Long findBySlug(String slug)
    {
        return baseDao.queryForObject("SELECT id FROM blog_category WHERE slug=?", Long.class, slug);
    }

    @Override
    public void add(Map<String, Object> record) throws Exception
    {
        baseDao.insert("blog_category", record);
    }

    @Override
    public List<Map<String, Object>> findAll()
    {
        return baseDao.query("SELECT * FROM blog_category");
    }

    @Override
    public void delete(String id) throws Exception
    {
        String sql0 = "UPDATE blog_category_relation SET category_id=0 WHERE category_id=?";
        String sql1 = "DELETE FROM blog_category WHERE id=? AND id>0";

        baseDao.update(sql0, id);
        baseDao.update(sql1, id);
    }

    @Override
    public boolean isSlugUnique(String slug)
    {
        List<Map<String, Object>> list = baseDao.query("SELECT 1 FROM blog_category WHERE slug=?", slug);
        return CollectionUtils.isEmpty(list);
    }
}
